<template>
  <div class="avatar-upload">
    <FileUpload
      accept="image/*"
      :loading="isUploading"
      loading-text="上传头像中..."
      :max-size="5 * 1024 * 1024"
      aria-label="上传头像"
      @file-selected="handleFileSelected"
      @file-error="handleFileError"
    >
      <div class="avatar-container">
        <a-avatar :size="size" :src="avatarUrl">
          {{ fallbackText }}
        </a-avatar>
        <div class="avatar-overlay">
          <CameraOutlined />
          <span>更换头像</span>
        </div>
      </div>
    </FileUpload>
    
    <div v-if="isUploading" class="upload-progress">
      <a-spin size="small" />
      <span>上传中...</span>
    </div>
    
    <p class="avatar-hint">{{ hint }}</p>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { message } from 'ant-design-vue'
import { CameraOutlined } from '@ant-design/icons-vue'
import FileUpload from './FileUpload.vue'
import { apiService } from '@/services/api'
import type { UploadResult } from '@/types'

interface Props {
  modelValue?: string // 头像URL
  size?: number
  fallbackText?: string
  hint?: string
}

interface Emits {
  (e: 'update:modelValue', value: string): void
  (e: 'upload-success', result: UploadResult): void
  (e: 'upload-error', error: string): void
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: '',
  size: 100,
  fallbackText: '头像',
  hint: '点击头像更换图片，支持 JPG、PNG、GIF、WebP 格式，最大 5MB'
})

const emit = defineEmits<Emits>()

const isUploading = ref(false)

const avatarUrl = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 处理文件选择
const handleFileSelected = async (files: File[]) => {
  if (files.length === 0) return

  const file = files[0]
  
  // 额外的图片类型验证
  if (!file.type.startsWith('image/')) {
    message.error('请选择图片文件')
    return
  }

  // 支持的图片格式
  const supportedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp']
  if (!supportedTypes.includes(file.type)) {
    message.error('只支持 JPG、PNG、GIF、WebP 格式的图片')
    return
  }

  try {
    isUploading.value = true
    
    // 调用API上传文件
    const result: UploadResult = await apiService.uploadAvatar(file)
    
    // 构建完整的头像URL
    const baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5276/api'
    const staticBaseUrl = baseUrl.replace('/api', '')
    const fullAvatarUrl = `${staticBaseUrl}${result.url}`
    
    // 更新头像URL
    avatarUrl.value = fullAvatarUrl
    
    message.success('头像上传成功')
    emit('upload-success', result)
    
  } catch (error: any) {
    console.error('Avatar upload error:', error)
    const errorMessage = error.response?.data?.message || '头像上传失败'
    message.error(errorMessage)
    emit('upload-error', errorMessage)
  } finally {
    isUploading.value = false
  }
}

// 处理文件错误
const handleFileError = (error: string) => {
  message.error(error)
  emit('upload-error', error)
}

// 预览图片（可选功能）
const previewImage = (file: File): Promise<string> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = (e) => resolve(e.target?.result as string)
    reader.onerror = reject
    reader.readAsDataURL(file)
  })
}
</script>

<style scoped>
.avatar-upload {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar-container {
  position: relative;
  cursor: pointer;
  margin-bottom: 8px;
  transition: transform 0.2s ease;
}

.avatar-container:hover {
  transform: scale(1.05);
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  opacity: 0;
  transition: opacity 0.3s ease;
  font-size: 12px;
  pointer-events: none;
}

.avatar-container:hover .avatar-overlay {
  opacity: 1;
}

.avatar-overlay span {
  margin-top: 4px;
  font-size: 12px;
}

.upload-progress {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
  font-size: 14px;
  margin-bottom: 8px;
}

.avatar-hint {
  margin: 8px 0 0 0;
  color: #666;
  font-size: 12px;
  text-align: center;
  max-width: 200px;
  line-height: 1.4;
}

/* 禁用状态 */
.avatar-upload.disabled .avatar-container {
  cursor: not-allowed;
  opacity: 0.5;
}

.avatar-upload.disabled .avatar-container:hover {
  transform: none;
}

.avatar-upload.disabled .avatar-overlay {
  display: none;
}
</style>
